﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace parkMonitor.DataBase
{
    interface IDBOperation
    {
        MySqlDataReader getResultSet(ref int count);
        void getInsert();
        void getUpdate();
        void getDelete();
    }
    class Operation : IDBOperation
    {
        DBConnection connection = null;
        MySqlConnection con = null;
        MySqlCommand cmd = null;
        MySqlDataReader reader = null;
        public Operation(string connectionStr, string sql)
        {
            connection = new DBConnection();
            con = connection.getConn(connectionStr);
            cmd = connection.getComm(sql, con);
        }
        /// <summary>
        /// 数据库查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public MySqlDataReader getResultSet(ref int count)
        {
            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (reader.HasRows)
                    {
                        count++;
                        //return reader;
                    }                 
                }               
            }
            catch
            {
                Console.WriteLine("数据库异常");
            }
            return reader;
        }

        public void getInsert()
        {
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                Console.WriteLine("插入异常");
            }
        }

        public void getUpdate()
        {
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                Console.WriteLine("更新异常");
            }
        }

        public void getDelete()
        {
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                Console.WriteLine("删除异常");
            }
        }
        public int getInsertId()
        {
            int insertID = 0;
            try
            {
                insertID = Convert.ToInt32(cmd.LastInsertedId);
            }
            catch
            {
                Console.WriteLine("插入数据库失败");
            }
            return insertID;
        }

        public void DBClose()
        {
            if (reader != null)
            {
                reader.Close();
                reader.Dispose();
            }
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (con != null)
            {
                con.Close();
                con.Dispose();
            }
        }
    }
}
